package com.csdn.ingo.dao.ctrip.search.dictionary.productscore;

import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.Set;

public class Similarty {
  Map<Character, int[]> vectorMap = Maps.newHashMap();

  int[] tempArray = null;

  public Similarty(String string1, String string2) {
    for (Character character1 : string1.toCharArray()) {
      if (vectorMap.containsKey(character1)) {
        vectorMap.get(character1)[0]++;
      } else {
        tempArray = new int[2];
        tempArray[0] = 1;
        tempArray[1] = 0;
        vectorMap.put(character1, tempArray);
      }
    }
    for (Character character2 : string2.toCharArray()) {
      if (vectorMap.containsKey(character2)) {
        vectorMap.get(character2)[1]++;
      } else {
        tempArray = new int[2];
        tempArray[0] = 0;
        tempArray[1] = 1;
        vectorMap.put(character2, tempArray);
      }
    }
  }

  // 求余弦相似度+
  public double sim() {
    double result;
    result = pointMulti(vectorMap) / sqrtMulti(vectorMap);
    return result;
  }

  private double sqrtMulti(Map<Character, int[]> paramMap) {
    double result;
    result = squares(paramMap);
    result = Math.sqrt(result);
    return result;
  }

  // 求平方和
  private double squares(Map<Character, int[]> paramMap) {
    double result1 = 0;
    double result2 = 0;
    Set<Character> keySet = paramMap.keySet();
    for (Character character : keySet) {
      int temp[] = paramMap.get(character);
      result1 += (temp[0] * temp[0]);
      result2 += (temp[1] * temp[1]);
    }
    return result1 * result2;
  }

  // 点乘法
  private double pointMulti(Map<Character, int[]> paramMap) {
    double result = 0;
    Set<Character> keySet = paramMap.keySet();
    for (Character character : keySet) {
      int temp[] = paramMap.get(character);
      result += (temp[0] * temp[1]);
    }
    return result;
  }

  public static double getSimValue(String s1, String s2) {
    if (StringUtils.isEmpty(s1) || StringUtils.isEmpty(s2)) {
      return 0;
    }
    return new Similarty(s1, s2).sim();
  }


  public static void main(String[] arg) {
    System.out.println(getSimValue("学院奖", "安康学院江南校区-创名会计"));
  }

}
